'''
中老年防癌医疗险
'''

import sys
import warnings
warnings.filterwarnings('ignore')
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,execjs,re,json
from urllib.parse import  urlencode
from common.helper import Helper

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "中老年防癌医疗险"
    # 生成产品数据
    def genProductInfo(self):

        plan = {
            # 年龄段
            "year":[str(i) for i in range(45,81)],
            #有无社保
            "socialSec":["Y","N"],
            # 计划
            "plan":["1万免赔额度","0免赔额度"],
            #保障期限
            "expire":["1年"]
        }
        for v in product( plan["year"],plan["socialSec"],plan["plan"],plan["expire"]):

            planCode = "WTI_MB_B" if v[2] == "0免赔额度" else "WTI_MB_T"

            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( v[0],v[1],v[2],planCode,v[3]))
            self.mysql._conn.commit()
            print( domain[self.name]["insert_sql"].format( v[0],v[1],v[2],planCode,v[3]) )


    # 执行爬虫
    def requestJson(self,dt=None):


        data = {

            "socialSec":"WTI_MB_"+dt["socialSec"],
            "planCode":dt["planCode"],
            "year":51

        }


        params = self.scriptJS( data )

        print( params )
        data = {

            "productCode": params,
            "insuranceCode": "WTI",
            "isApplyCar": "0",
            "insuranceCount": "1",
            "backUp1":params,
            "_action": "commonCalculateFee"
        }

        payload = urlencode( data )

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and "null" in r.text:

            pattern = re.search(r"{'err':null,'result':{'SUM_PREMIUM':'(.*)','SUM_INSURED':'1000000.0'}}",r.text).group(1)

            price = Helper.decimalParse( pattern )

            data = {

                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            self.mysql.updatePrice(data)

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

            print("产品价格更新失败:", dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)


    def scriptJS(self,data):


        js = '''
        
            /*
            
            WTI_MB_B -- > 0免赔
            
            WTI_MB_T -- > 1万免赔
            
            WTI_MB_Y --> 有社保
            
            WTI_MB_N --> 无社保
            
            
            */
            
            function calculatePremium( data ) {
            
                var shebao = data["socialSec"];
                var scheme = data["planCode"]
            
                var age = data["year"];
            
                // shebao = $(".form-fasizeb").val();
                // scheme=$(".form-fasize").val();
            
                // var  birthDate= getBirthdayByID(id);
                // var age = getBirthdayAge(birthDate);
            
                if (scheme == "WTI_MB_B") {
                    if (shebao == "WTI_MB_Y") {
                        if (age == 45) {
                            return("WTI_MB_ZLNFA_B_Y_1");
                        } else if (age <= 50 && age >= 46) {
                            return("WTI_MB_ZLNFA_B_Y_2");
                        } else if (age <= 55 && age >= 51) {
                            return("WTI_MB_ZLNFA_B_Y_3");
                        } else if (age <= 60 && age >= 56) {
                            return("WTI_MB_ZLNFA_B_Y_4");
                        } else if (age <= 65 && age >= 61) {
                            return("WTI_MB_ZLNFA_B_Y_5");
                        } else if (age <= 70 && age >= 66) {
                            return("WTI_MB_ZLNFA_B_Y_6");
                        } else if (age <= 75 && age >= 71) {
                            return("WTI_MB_ZLNFA_B_Y_7");
                        } else if (age <= 80 && age >= 76) {
                            return("WTI_MB_ZLNFA_B_Y_8");
                        } else if (age <= 85 && age >= 81) {
                            return("WTI_MB_ZLNFA_B_Y_9");
                        }
                    } else {
                        if (age == 45) {
                            return("WTI_MB_ZLNFA_B_N_1");
                        } else if (age <= 50 && age >= 46) {
                            return("WTI_MB_ZLNFA_B_N_2");
                        } else if (age <= 55 && age >= 51) {
                            return("WTI_MB_ZLNFA_B_N_3");
                        } else if (age <= 60 && age >= 56) {
                            return("WTI_MB_ZLNFA_B_N_4");
                        } else if (age <= 65 && age >= 61) {
                            return("WTI_MB_ZLNFA_B_N_5");
                        } else if (age <= 70 && age >= 66) {
                            return("WTI_MB_ZLNFA_B_N_6");
                        } else if (age <= 75 && age >= 71) {
                            return("WTI_MB_ZLNFA_B_N_7");
                        } else if (age <= 80 && age >= 76) {
                            return("WTI_MB_ZLNFA_B_N_8");
                        } else if (age <= 85 && age >= 81) {
                            return("WTI_MB_ZLNFA_B_N_9");
                        }
                    }
                } else {
                    if (shebao == "WTI_MB_Y") {
                        if (age ==45) {
                            return("WTI_MB_ZLNFA_A_Y_1");
                        } else if (age <= 50 && age >= 46) {
                            return("WTI_MB_ZLNFA_A_Y_2");
                        } else if (age <= 55 && age >= 51) {
                            return("WTI_MB_ZLNFA_A_Y_3");
                        } else if (age <= 60 && age >= 56) {
                            return("WTI_MB_ZLNFA_A_Y_4");
                        } else if (age <= 65 && age >= 61) {
                            return("WTI_MB_ZLNFA_A_Y_5");
                        } else if (age <= 70 && age >= 66) {
                            return("WTI_MB_ZLNFA_A_Y_6");
                        } else if (age <= 75 && age >= 71) {
                            return("WTI_MB_ZLNFA_A_Y_7");
                        } else if (age <= 80 && age >= 76) {
                            return("WTI_MB_ZLNFA_A_Y_8");
                        } else if (age <= 85 && age >= 81) {
                            return("WTI_MB_ZLNFA_A_Y_9");
                        }
                    } else {
                        if (age == 45) {
                            return("WTI_MB_ZLNFA_A_N_1");
                        } else if (age <= 50 && age >= 46) {
                            return("WTI_MB_ZLNFA_A_N_2");
                        } else if (age <= 55 && age >= 51) {
                            return("WTI_MB_ZLNFA_A_N_3");
                        } else if (age <= 60 && age >= 56) {
                            return("WTI_MB_ZLNFA_A_N_4");
                        } else if (age <= 65 && age >= 61) {
                            return("WTI_MB_ZLNFA_A_N_5");
                        } else if (age <= 70 && age >= 66) {
                            return("WTI_MB_ZLNFA_A_N_6");
                        } else if (age <= 75 && age >= 71) {
                            return("WTI_MB_ZLNFA_A_N_7");
                        } else if (age <= 80 && age >= 76) {
                            return("WTI_MB_ZLNFA_A_N_8");
                        } else if (age <= 85 && age >= 81) {
                            return("WTI_MB_ZLNFA_A_N_9");
                        }
                    }
            
                }
            
            }
            
            

        '''

        cxt = execjs.compile( js )

        result  = cxt.call("calculatePremium",data)

        return result

